// pages/user/user.js
import { checkLogin, getUserInfo } from "../../utils/login"
import { bind } from "../../server/bind"
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import {outLogin} from "../../server/login"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    checkLogin()
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    // console.log(this.data.userInfo);
  },
  bindorUnbind() {
    wx.showModal({
      title: '提示',
      content: this.data.userInfo.openid ? '请确认是否解绑' : '请确认是否绑定',
      success: res => {
        if (res.confirm) {
          let data = {
            type: "unbind",
            openid: wx.getStorageSync('openid')
          }
          if (!this.data.userInfo.openid) data.type = "bind"
          bind(data).then(res => {
            // console.log(res);
            let msg = this.data.userInfo.openid ? '解绑成功' : '绑定成功'
            getUserInfo().then(() => {
              Toast.success(msg)
              this.setData({
                userInfo: wx.getStorageSync('userInfo')
              })
            })
          })
        }
      }
    })
  },
  logOutClick(){
    outLogin().then(res =>{
      // console.log(res);
      wx.removeStorageSync('access_token');
      wx.removeStorageSync('userInfo')
      Toast({
        type: 'success',
        message: '退出成功',
        onClose: () => {
          wx.reLaunch({
            url: '/pages/index/index',
          })
        },
      });
    })
  },
})